<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>注册</title>
    <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="./utils/bootstrap.min.css" />
    <link rel="stylesheet" href="./css/register.min.css" />
    <script src="./utils/jquery-3.5.1.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="registerBox">
        <img src="./img/register/logo.png" alt="" />
        <form>
          <!-- 用户名 -->
          <div>
            <input
              id="name"
              type="text"
              class="form-control input-register"
              placeholder="用户名"
            />
          </div>
          <!-- 手机号 -->
          <div>
            <input
              id="phone"
              type="text"
              class="form-control input-register"
              placeholder="手机号码"
            />
          </div>
          <!-- 密码 -->
          <div>
            <input
              id="password"
              type="password"
              class="form-control input-register"
              value="密码"
            />
          </div>
          <!-- 确认密码 -->
          <div>
            <input
              id="passwordConfirm"
              type="password"
              class="form-control input-register"
              value="确认密码"
            />
            <div class="invalid-feedback">第二次输入与第一次不一致</div>
          </div>

          <button type="button" class="btn btn-primary" id="registerBtn">
            注册并登录
          </button>
        </form>

        <div class="about-register">
          <a href="login.html">已有账号去注册</a>
        </div>
      </div>
    </div>

    <script>
      function isSame() {
        const password = $("#password").val();
        const passwordConfirm = $("#passwordConfirm").val();
        if (password == passwordConfirm) {
          $("#passwordConfirm").toggleClass("is-valid");
          return true;
        } else {
          $("#passwordConfirm").toggleClass("is-invalid");
          return false;
        }
      }

      //点击注册
      $("#registerBtn").click(function () {
        if (!isSame()) return;
        const phone = $("#phone").val();
        const name = $("#name").val();
        const password = $("#password").val();

        $.ajax({
          // 前后端接口
          url: "/students/register",
          type: "POST",
          data: { name, phone, password },
          success(res) {
            console.log("后端返回结果：", res);
            if (res.code !== 200) return alert(res.message);
            alert("注册成功");
            location.href = "login.html";
          }
        });
      });
    </script>
  </body>
</html>
